package es.upv.epsa.mobweb.moneyback;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.ObjectMapper;

import es.upv.epsa.mobweb.moneyback.database.Item;
import es.upv.epsa.mobweb.moneyback.json.JSONParser;

public class ItemActivity extends Activity {
	
	private JSONParser 		jsonParser;
	private ObjectMapper  	mapper 		= new ObjectMapper();
	private int				itemId		= 0;
	private int				friendId 	= 0;
	private int				accountid	= 0;
	private String			server_url;
	
	private EditText 		tName;
	private EditText 		tDescription;
	private EditText 		tAmmount;
	private Button			bOk;
	private Button			btnDelete;
	
	private Item			item 		= null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.item);
		
		jsonParser 	= new JSONParser();
		
		if(getIntent().getExtras() != null){
			if(getIntent().getExtras().getString("id") != null)
				itemId 		= Integer.valueOf(getIntent().getExtras().getString("id"));
			
			if(getIntent().getExtras().getString("friendId") != null)
				friendId 	= Integer.valueOf(getIntent().getExtras().getString("friendId"));
			
			if(getIntent().getExtras().getString("accountid") != null)
				accountid	= Integer.valueOf(getIntent().getExtras().getString("accountid"));
		}
		
		setWidgets();
		
		if(itemId != 0)
			getItemData();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.item, menu);
		return true;
	}
	
	private void setWidgets(){
		server_url		= getResources().getString(R.string.server_url) + 
					  	  getResources().getString(R.string.items_url);
		
		bOk 			= (Button)		findViewById(R.id.okButton);
		btnDelete		= (Button) 		findViewById(R.id.btnDelete);
		tName 			= (EditText)	findViewById(R.id.name);
		tDescription 	= (EditText)	findViewById(R.id.description);
		tAmmount 		= (EditText)	findViewById(R.id.ammount);
		
		bOk.setOnClickListener(new OnClickListener() {
		    @Override
		    public void onClick(View v){
		    	String name 		= tName.getText().toString();
		    	String description 	= tDescription.getText().toString();
		    	float amount 		= Float.parseFloat(tAmmount.getText().toString());
		    	
		    	if(itemId == 0){
		    		addItem(name, description, amount);
		    	}else{
		    		// Modify
		    	}
		    }
		});
		
		btnDelete.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View view) {
				new AlertDialog.Builder(ItemActivity.this)
				.setIcon(android.R.drawable.ic_dialog_alert)
				.setTitle("Forgive Item")
				.setMessage("Are you sure you want to forgive this item?")
				.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
					@Override
					public void onClick(DialogInterface dialog, int which) {
						deleteItem();
					}

				})
				.setNegativeButton("No", null)
				.show();
			}
			
		});
		
		if(itemId != 0){
			btnDelete.setVisibility(View.VISIBLE);
		}
	}
	
	private void addItem(String name, String description, float amount){
		JsonFactory 			jfactory 	= new JsonFactory();
		ByteArrayOutputStream 	bout 		= new ByteArrayOutputStream();
		JsonGenerator 			jGenerator;

		try {
			jGenerator = jfactory.createJsonGenerator(new OutputStreamWriter(bout, "UTF-8"));
			jGenerator.writeStartObject();

			jGenerator.writeNumberField("action", 1);
			jGenerator.writeStringField("name", name);
			jGenerator.writeStringField("description", description);
			jGenerator.writeNumberField("amount", amount);
			jGenerator.writeNumberField("idaccount", accountid);

			jGenerator.writeEndObject();
			jGenerator.close();

			new SendJSON(bout.toString(), 3).execute();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void deleteItem(){
		JsonFactory 			jfactory 	= new JsonFactory();
		ByteArrayOutputStream 	bout 		= new ByteArrayOutputStream();
		JsonGenerator 			jGenerator;

		try {
			jGenerator = jfactory.createJsonGenerator(new OutputStreamWriter(bout, "UTF-8"));
			jGenerator.writeStartObject();

			jGenerator.writeNumberField("action", 3);
			jGenerator.writeNumberField("id", itemId);

			jGenerator.writeEndObject();
			jGenerator.close();

			new SendJSON(bout.toString(), 3).execute();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void getItemData(){
		JsonFactory 			jfactory 	= new JsonFactory();
		ByteArrayOutputStream 	bout 		= new ByteArrayOutputStream();
		JsonGenerator 			jGenerator;

		try {
			jGenerator = jfactory.createJsonGenerator(new OutputStreamWriter(bout, "UTF-8"));
			jGenerator.writeStartObject();

			jGenerator.writeNumberField("action", 5);
			jGenerator.writeNumberField("id", itemId);

			jGenerator.writeEndObject();
			jGenerator.close();

			new SendJSON(bout.toString(), 0).execute();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private class SendJSON extends AsyncTask<Void, Void, Void>{
		String 			json 	= "";
		int		 		action 	= 0;
		String 			data 	= "";
		ProgressDialog 	dialog;
		
		public SendJSON(String json, int action){
			this.json 	= json;
			this.action	= action;
		}
		
		@Override
		protected Void doInBackground(Void... arg0) {
			data = jsonParser.sendJSON(server_url, json);
			
			return null;
		}
		
		@Override
		protected void onPreExecute(){
			dialog = ProgressDialog.show(ItemActivity.this, "", "Loading item...", true);
			dialog.setCancelable(false);
			dialog.setOnCancelListener(new OnCancelListener(){

				@Override
				public void onCancel(DialogInterface dialog) {

				}
				
			});
		}
		
		@Override
		protected void onPostExecute(Void result){
			dialog.dismiss();
			
			if(action == 0){
				parseJSONItem(data);
			}else if(action == 1){
				// Add Item
				finish();
			}else{
				// Delete
				finish();
			}
		}
	}
	
	private void parseJSONItem(String json){
		try {
			JsonFactory jfactory = new JsonFactory();
			JsonParser jparser = jfactory.createJsonParser(json);

			while(jparser.nextToken() == JsonToken.START_OBJECT){
				item = new Item();
				item = mapper.readValue(jparser, Item.class);
				
				tName.setText(item.getName());
				tDescription.setText(item.getDescription());
				tAmmount.setText(String.valueOf(item.getAmount()));
			}

			jparser.close();
			
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
